package com.wodsy.phoenix.datadao.goodsc.dao.impl;

import java.util.List;

import org.apache.lucene.analysis.WhitespaceAnalyzer;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.Query;
import org.apache.lucene.util.Version;
import org.hibernate.CacheMode;
import org.hibernate.FlushMode;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.search.FullTextQuery;
import org.hibernate.search.FullTextSession;
import org.hibernate.search.Search;
import org.hibernate.search.query.dsl.QueryBuilder;
import org.hibernate.search.query.engine.spi.FacetManager;
import org.hibernate.search.query.facet.Facet;
import org.hibernate.search.query.facet.FacetingRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Repository;

import com.wodsy.phoenix.datadao.base.BaseHibernateDao;
import com.wodsy.phoenix.datadao.goodsc.dao.SearchGoodsDao;
import com.wodsy.phoenix.dataobject.goodsc.model.search.SearchGoods;

@Repository("searchGoodsDao")
public class SearchGoodsDaoImpl extends BaseHibernateDao<SearchGoods, Long>
		implements SearchGoodsDao {

	@Override
	@Autowired
	@Qualifier(value = "goodsc")
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;

	}

	@Override
	public Class<SearchGoods> getModelClass() {
		return SearchGoods.class;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<SearchGoods> searchGoodsBykey(String key,int min,int max) {
		Session session = getSession();

		FullTextSession fullTextSession = Search.getFullTextSession(session);
		// fullTextSession.beginTransaction();

		QueryParser queryParser = new QueryParser(Version.LUCENE_36, "name",
				new WhitespaceAnalyzer(Version.LUCENE_36));

		Query luceneQuery = null;

		try {
			luceneQuery = queryParser.parse(key);
		} catch (ParseException e) {
			e.printStackTrace();
		}

		QueryBuilder queryBuilder = fullTextSession.getSearchFactory()
				.buildQueryBuilder().forEntity(getModelClass()).get();

		FullTextQuery fullTextQuery = fullTextSession.createFullTextQuery(
				luceneQuery, getModelClass());
		
		FacetingRequest priceFacetingRequest = null;
		
		if(min >0  && max >0){
			priceFacetingRequest = queryBuilder.facet()
				.name("priceFacet").onField("price").range()
				.from(min).to(max+1)
				.createFacetingRequest();
		}else if(min>0 && max == 0){
			priceFacetingRequest = queryBuilder.facet()
					.name("priceFacet").onField("price").range()
					.above(min).excludeLimit()
					.createFacetingRequest();
		}else if(min == 0 && max > 0){
			priceFacetingRequest = queryBuilder.facet()
					.name("priceFacet").onField("price").range()
					.below(max).excludeLimit()
					.createFacetingRequest();
		}

		if(min!=0 || max!=0){
			FacetManager facetManager = fullTextQuery.getFacetManager();

			facetManager.enableFaceting(priceFacetingRequest);

			List<Facet> priceFacets = facetManager.getFacets("priceFacet");
			
			facetManager.getFacetGroup("priceFacet").selectFacets(
				priceFacets.get(0));
		}

		List<SearchGoods> list = fullTextQuery.list();

//		// 结果集关键字高亮
//		SimpleHTMLFormatter formatter = new SimpleHTMLFormatter(
//				"<font color=\"red\">", "</font>");
//		QueryScorer queryScorer = new QueryScorer(luceneQuery);
//		Highlighter highlighter = new Highlighter(formatter, queryScorer);
//		Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_36);
//		String[] fieldNames = { "name" };
//		for (SearchGoods sg : list) {
//			for (String fieldName : fieldNames) {
//				// 运用反射得到具体的Name
//				Object fieldValue = ReflectionUtils.invokeMethod(BeanUtils
//						.getPropertyDescriptor(getModelClass(), fieldName)
//						.getReadMethod(), sg);
//				String hightLightFieldValue = null;
//				if (fieldValue instanceof String) {
//
//					try {
//						// 获得高亮关键字
//						hightLightFieldValue = highlighter.getBestFragment(
//								analyzer, fieldName,
//								ObjectUtils.toString(fieldValue, null));
//					} catch (IOException e1) {
//						e1.printStackTrace();
//					} catch (InvalidTokenOffsetsException e1) {
//						e1.printStackTrace();
//					}
//					// 这个判断很关键，否则如果name中没有关键字的话，就会出现不显示的问题。
//					if (hightLightFieldValue != null) {
//						// 运用反射设置结果集中的关键字高亮
//						ReflectionUtils.invokeMethod(
//								BeanUtils.getPropertyDescriptor(
//										getModelClass(), fieldName)
//										.getWriteMethod(), sg,
//								hightLightFieldValue);
//					}
//				}
//			}
//		}
		return list;
	}

	@Override
	public void index() {

		try {
			Session session = getSession();

			FullTextSession fullTextSession = Search
					.getFullTextSession(session);

			fullTextSession.setFlushMode(FlushMode.MANUAL);
			fullTextSession.setCacheMode(CacheMode.IGNORE);
			Transaction transaction = fullTextSession.beginTransaction();

			org.hibernate.Query query = session.createQuery("from SearchGoods");

			@SuppressWarnings("unchecked")
			List<SearchGoods> list = query.list();
			System.out.println("---------------------" + list.size());
			for (SearchGoods sg : list) {
				System.out.println("---------------------"
						+ sg.getGoodsSaleProperty().getPopularity());
				fullTextSession.index(sg);
			}
			fullTextSession.flushToIndexes(); // apply changes to indexes
			fullTextSession.clear(); // free memory since the queue is processed
			transaction.commit();
			// session.close();
		} catch (Exception e) {
			// TODO: handle exception
		}

	}

}
